package cn.dgiot.fd.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.dgiot.fd.dao.IDeviceUpgradeDAO;
import cn.dgiot.fd.model.DeviceStateModel;
import cn.dgiot.fd.model.DeviceUpgradeModel;
import cn.dgiot.fd.service.IDeviceStateService;
import cn.dgiot.fd.service.IDeviceUpgradeService;

/**
 * [设备升级记录]
 * @author
 *
 */
@Service
public class DeviceUpgradeServiceImpl implements IDeviceUpgradeService{

	@Autowired
	private IDeviceUpgradeDAO deviceUpgradeDAO;

	@Autowired
	private IDeviceStateService deviceStateService;
	
	@Override
	public DeviceUpgradeModel getDeviceUpgrade(DeviceUpgradeModel deviceUpgradeModel) {
		// TODO Auto-generated method stub
		return deviceUpgradeDAO.getDeviceUpgrade(deviceUpgradeModel);
	}

	@Override
	public void insertDeviceUpgrade(DeviceUpgradeModel deviceUpgradeModel) {
		List<String> deviceNames = deviceUpgradeModel.getDeviceNames();
		List<DeviceUpgradeModel> deviceUpgradeModelList = new ArrayList<DeviceUpgradeModel>();
		for(int i=0;i<deviceNames.size();i++) {
			String deviceName = deviceNames.get(i);
			String productKey = deviceUpgradeModel.getProductKey();
			DeviceUpgradeModel result = deviceUpgradeDAO.getDeviceUpgrade(new DeviceUpgradeModel(deviceName, productKey));
			
			DeviceUpgradeModel param = new DeviceUpgradeModel();
			param.setDeviceName(deviceName);
			param.setProductKey(productKey);
			param.setJobId(deviceUpgradeModel.getJobId());
			param.setStatus(deviceUpgradeModel.getStatus());
			param.setCreateTime(deviceUpgradeModel.getCreateTime());
			if(result != null) {
				deviceUpgradeDAO.updateDeviceUpgrade(param);
			}else {
		    	DeviceStateModel deviceStateModel = new DeviceStateModel();
		    	deviceStateModel.setDeviceName(deviceName);
		    	deviceStateModel.setProductKey(deviceUpgradeModel.getProductKey());
		    	DeviceStateModel deviceStateModelResult = deviceStateService.getDeviceState(deviceStateModel);
				param.setIotId(deviceStateModelResult.getIotId());
				param.setId(UUID.randomUUID().toString().replace("-", ""));
				deviceUpgradeModelList.add(param);
			}
		}
		if(deviceUpgradeModelList != null && deviceUpgradeModelList.size() > 0) {
			deviceUpgradeDAO.insertDeviceUpgrade(deviceUpgradeModelList);
		}
	}

	@Override
	public void updateDeviceUpgradeStatus(DeviceUpgradeModel deviceUpgradeModel) {
		// TODO Auto-generated method stub
		deviceUpgradeDAO.updateDeviceUpgradeStatus(deviceUpgradeModel);
	}

}
